package cn.feilue.app.service.send;

import cn.feilue.app.service.commone.SendEmailError;
import cn.feilue.app.service.config.EmailConfig;
import cn.feilue.app.service.config.RedisUtilDes;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.feilue.app.service.commone.Constants.*;

/**
 * @author hongtao
 *
 *
 */
@Component
public class SendEmail {
    private static Logger log =   LoggerFactory.getLogger(SendEmail.class);
    private static AtomicInteger rout =  new AtomicInteger(1);
    private Map<String,AtomicInteger> errorEmail = new HashMap<>();
    private long delay=500;
    private String emailFromEmail;
    @Autowired
    private EmailConfig emailConfig;
/*    @Autowired
    private RedisUtilDes redisUtil;*/


/*    @PostConstruct
    public void init(){
        //初始化邮箱路由参数
        rout.set(emailConfig.getEmailList().size());
    }*/

    private EmailConfig.Email getEmail(){
//       int index =  rout.incrementAndGet() % emailConfig.getEmailList().size();
        EmailConfig.Email email = emailConfig.getEmailList().get(0);
        delay = email.getDelay();
        emailFromEmail = email.getFromEmail();
       return email;

    }

    /**
     *  这里可以做 动态邮箱 服务账号去发送针对 公共发送邮件有限制
     *  若限制严重 需要自己搭建邮件服务器
     * @param emailHost
     * @param transportType
     * @param fromEmail
     * @param authCode
     */
    public SendEmail(String emailHost,String transportType,String fromEmail,String authCode) {
//        this.emailHost = emailHost;
//        this.transportType = transportType;
//        this.fromEmail = fromEmail;
//        this.authCode = authCode;
    }

    public SendEmail() {
    }

    public void sendToEmail(String toEmail, String subject, String content) throws UnsupportedEncodingException, MessagingException {
        if (toEmail.isEmpty()) {
            return;
        }


        //初始化默认参数
        EmailConfig.Email email = getEmail();
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", email.getTransportType());
        props.setProperty("mail.host", email.getEmailHost());
        props.setProperty("mail.user", email.getFromUser());
        props.setProperty("mail.from", email.getFromEmail());
        //获取Session对象
        Session session = Session.getInstance(props, null);
        //开启后有调试信息
        session.setDebug(false);

        //通过MimeMessage来创建Message接口的子类
        MimeMessage message = new MimeMessage(session);

        String formName = MimeUtility.encodeWord("涛涛") + " <" + email.getFromEmail() + ">";
        InternetAddress from = new InternetAddress(formName);
        message.setFrom(from);

        //设置收件人：
        InternetAddress to = new InternetAddress(toEmail);
        message.setRecipient(Message.RecipientType.TO, to);



        //设置邮件主题
        message.setSubject(subject);

        //设置邮件内容,这里我使用html格式，其实也可以使用纯文本；纯文本"text/plain"
        message.setContent(content, "text/html;charset=UTF-8");

        //保存上面设置的邮件内容
        message.saveChanges();

        //获取Transport对象
        Transport transport = session.getTransport();
        //smtp验证，就是你用来发邮件的邮箱用户名密码（若在之前的properties中指定默认值，这里可以不用再次设置）
        transport.connect(email.getEmailHost(), email.getFromEmail(), email.getAuthCode());
        //发送邮件
        transport.sendMessage(message, message.getAllRecipients()); // 发送
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 群发邮件
     *
     * @param toEmails
     * @param subject
     * @param content
     */
    public void sendToEmails(List<String> toEmails, String subject, String content) {
        if (toEmails.isEmpty()) {
            return;
        }
        toEmails.forEach(entity -> {
            boolean isSendSuccess = true;
            try {
                sendToEmail(entity, subject, content);
            } catch (Exception e) {
                SendEmailError  error = new SendEmailError();
                error.setToEmails(entity);
                error.setSubject(subject);
                error.setContent(content);
                error.setEmailFromEmail(emailFromEmail);
                error.setErrorLog(e.getMessage());
                log.error("邮件发送错误："+error);
               /* redisUtil.put(SEND_EMAIL_ERROR,entity, JSON.toJSON(error).toString());
                Object tempCount = redisUtil.getHashKey(EMAIL_HOST, emailFromEmail);
                tempCount = tempCount == null ? 0 : tempCount;

                Integer count = Integer.parseInt(tempCount.toString());
                redisUtil.put(EMAIL_HOST,emailFromEmail,(++count).toString());
                isSendSuccess = false;*/
                e.printStackTrace();
            }

           /* if(isSendSuccess){
                try {
                    redisUtil.leftPush(SEND_EMAIL_HOST_LIST+":"+emailFromEmail,entity);
                } catch (Exception e) {
                    log.error("redis :"+e.getMessage());
                }
            }*/

        });
    }


}
